package com.hertz.alarm.util;


import java.net.URLEncoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;


public class RequestUtil {
	private  final static  Logger logger = LoggerFactory.getLogger(RequestUtil.class);
	
//	public  static  enum USERAGENT_TYPE{
//		unknow((String)"unknow"),
//		web((String)"web"),
//		android((String)"android"),
//		ios((String)"ios");
//		private USERAGENT_TYPE(String _code){
//			code = _code;
//		}
//		private final String code;
//		public String getCode(){
//			return code;
//		}
//	}
//	
//	
//	public static String getLoginedEncryptedUserInfo(HttpServletRequest request){
//		String ret = null;
//		Object obj = request.getAttribute(WebConstant.USER_LOGIN_COOKIE_NAME_VALUE);
//		if(obj != null){
//			ret = (String)obj;
//		}else{
//			Cookie [] cookies = request.getCookies();
//			if(cookies != null){
//				for(Cookie cookie:cookies){
//					if(WebConstant.USER_LOGIN_COOKIE_NAME.equalsIgnoreCase(cookie.getName())){						
//						ret = cookie.getValue();
//						request.setAttribute(WebConstant.USER_LOGIN_COOKIE_NAME_VALUE,ret);
//						break;
//					}
//				}
//			}
//		}
//		logger.debug("getLoginedEncryptedUserInfo ret:{}",ret);
//		return ret;
//	}
//	
//	public static String getEncryptUserInfo(long cuid){
//		Long logintime = System.currentTimeMillis()/1000;
//		String system_login_info = String.format("%d^_^un^_^%d^_^3232236882",cuid,logintime);
//		return XXTEA.encryptUserInfo(system_login_info);
//	}
//	
//	public static String shortUrl(String url){
//		String shortUrl 		= null;
//		
//		if(url == null || "".equals(url)){
//			return url; 
//		}
//
//		url = url.replaceFirst("http://","");
//		try {
//			String newUrl = String.format("%s%s%s", ApiUrlHelper.SHORT_URL_PREF,"/url/", URLEncoder.encode(url, "utf-8"));
//			shortUrl = HttpClientUtil.get(newUrl, null);
//			logger.debug("get shortUrl:{}",shortUrl);
//			shortUrl = String.format("%s%s",ApiUrlHelper.SHORT_URL_PREF,shortUrl);
//		} catch (Exception e) {
//			logger.error("shortUrl failured:{}",e);
//		}
//		
//       return shortUrl;
//	}
//	
//	@Transactional
//	public static UserDetail   getSessionUserDetail(HttpServletRequest request){
//		  UserDetail ud  = (UserDetail)request.getAttribute(WebConstant.USER_LOGIN_UD);
//		  if(ud != null) return ud;
//		  
//		  Long cuid = (Long)request.getAttribute(WebConstant.USER_LOGIN_COOKIE_NAME);
//		  if(cuid == null){
//			  cuid = getUserIdFromCookie(request); 
//		  }
//		  if(cuid == null || cuid <= 0)  return null;
//		  
//		  ud = userDetailService.get(cuid,true);
//		  if(ud == null){
//			  return null;
//		  }
//		  request.setAttribute(WebConstant.USER_LOGIN_UD, ud);
//		  return ud;
//	}
//	
//	/*public static Object    getSessionValue(HttpServletRequest request,String name){
//		HttpSession session = getSession(request);
//		if(session == null){
//			return null;
//		}
//		return session.getAttribute(name);
//	}
//	
//	public static HttpSession getSession(HttpServletRequest request){
//		return getSession(request,false);
//	}
//	
//	public static HttpSession getSession(HttpServletRequest request,boolean create){
//		return request.getSession(create);
//	}
//	
//	public static String getSessionId(HttpServletRequest request){
//		return RequestUtil.getSession(request).getId();
//	}*/
//	
//	public static Long   getUserIdFromCookie(HttpServletRequest request){
//		Long    uid     = null;
//		String userInfo = getUserInfoCookieValue(request);
//		String cookieUid = getCookieValue(request, WebConstant.USER_LOGIN_COOKIE_UID);
//		if(userInfo == null || "".equals(userInfo)) return null;
//		if(StringUtils.isBlank(cookieUid)) return null;
//		
//		userInfo = XXTEA.decryptUserInfo(userInfo);
//		String arr[] = userInfo.split("\\^_\\^");
//		if(arr.length > 2){
//			if(!arr[0].equals(cookieUid))
//				return uid;
//			uid = Long.valueOf((arr[0]));
//			request.setAttribute(WebConstant.USER_LOGIN_COOKIE_NAME,uid);
//			//UserDetail ud = userDetailService.get(uid);
//			//RequestUtil.getSession(request,true).setAttribute(Constant.USER_LOGIN_COOKIE_NAME, ud);
//		}
//		
//		return uid;
//	}
	
	public static void logout(HttpServletRequest request,HttpServletResponse response){
		delCookie(request, response, Constants4HTTP.SYS_TOKEN);
		delCookie(request, response, Constants4HTTP.SYS_UNAME);
		
	}
	
	
	public static String getCookieValue(HttpServletRequest request,String cookieName){
		String userInfo = null;
		Cookie [] cookies = request.getCookies();
		if(cookies != null){
			for(Cookie cookie:cookies){
				if(cookieName.equalsIgnoreCase(cookie.getName())){
					userInfo = cookie.getValue();
					break;
				}
			}
		}
		
		return  userInfo;
	}
	
	public static void delCookie(HttpServletRequest request,HttpServletResponse response,String cookieName){
		Cookie [] cookies = request.getCookies();
		if(cookies != null){
			for(Cookie cookie:cookies){
				if(cookieName.equalsIgnoreCase(cookie.getName())){
					 cookie.setMaxAge(0);
					 cookie.setDomain(".myiris.sinaapp.com");
					 cookie.setPath("/"); 
				     response.addCookie(cookie); 
					break;
				}
			}
		}
	}

	public static String generateToken(String str,String serial){
		return com.hertz.alarm.util.StringUtils.getMD5Str(str + serial);
	}
	
	public static void setCookie(HttpServletResponse response,String cookieName,String cookieValue){
		Cookie cookie = new Cookie(cookieName,cookieValue);
		cookie.setMaxAge(5*365*24*60*60);
		cookie.setDomain(".myiris.sinaapp.com");
		cookie.setPath("/");
		response.addCookie(cookie);
	}
	
	public static String getIpAddr(HttpServletRequest request){
		String ip = request.getHeader("X-Real-IP");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("X-Forwarded-For");		
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}		
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		String[] ips = ip.split(",");
		ip = ips[0];
		return ip;
	}
	
	
}